package com.facefun.service.Impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.facefun.Enum.StateCode;
import com.facefun.domain.User;
import com.facefun.domain.UserExample;
import com.facefun.service.UserService;
import com.facefun.util.FileUploadUtil;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class UserServiceImpl extends BaseService<User> implements UserService{

	@Override
	public Map<String, Object> getUserList(Integer offset, Integer limit) {
		Page<User> p=PageHelper.offsetPage(offset, limit).doSelectPage(new ISelect() {
					
			@Override
			public void doSelect() {
				selectAll();
				
			}
		});
		
		Long recordsTotal=p.getTotal();
		List<User> data=p.getResult();
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("recordsTotal", recordsTotal);
		map.put("recordsFiltered", recordsTotal);
		map.put("data", data);
		return map;
	}

	@Override
	public User addUser(User user, MultipartFile file, HttpServletRequest request) {
		UserExample example=new UserExample();
		example.createCriteria().andNameEqualTo(user.getName());
		List<User> users=mapper.selectByExample(example);
		if(users.size()!=0){
			throw new RuntimeException("用户已存在！");
		}
		if(!file.isEmpty()){
			String path=FileUploadUtil.upload(file, request);
			user.setHeadimg(path);
		}else{
			user.setHeadimg("/img/default.jpg");
		}
		save(user);
		return user;
	}
	

	@Override
	public User updateUser(User user, MultipartFile file, HttpServletRequest request) {
		
		if(!file.isEmpty()){
			String path=FileUploadUtil.uploadUpdate(file,user.getHeadimg(), request);
			user.setHeadimg(path);
		}
		updateNotNull(user);
		
		return selectByPrimaryKey(user.getId());
	}

}
